package com.yunshang.shoppingmall.shopping.User;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.yunshang.shoppingmall.common.*;

import com.yunshang.shoppingmall.entity.*;
import com.yunshang.shoppingmall.entity.Hsys.HsysUserData;
import com.yunshang.shoppingmall.entity.Hsys.HsysUserRoot;
import com.yunshang.shoppingmall.service.ConfigService;
import com.yunshang.shoppingmall.service.Finace.FinaceService;
import com.yunshang.shoppingmall.service.Finace.FinaceTotalService;
import com.yunshang.shoppingmall.service.SysUserNoService;
import com.yunshang.shoppingmall.service.User.UserNoService;
import com.yunshang.shoppingmall.service.UserService;
import com.yunshang.shoppingmall.shopping.WeChat.common.WinChat;
import com.yunshang.shoppingmall.shopping.WeChat.common.WinxinUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/wap")
public class UserRegisterAndLoginController {
    Logger logger = LoggerFactory.getLogger(UserRegisterAndLoginController.class);
    @Autowired
    SysUserNoService sysUserNoService;
    @Autowired
    UserService userService;
    @Autowired
    ConfigService configService;
    @Autowired
    UserNoService userNoService;
    @Autowired
    FinaceTotalService finaceTotalService;

    @Autowired
    FinaceService finaceService;

    @Autowired
    SmsDemo smsDemo;

    /*打开注册页面*/
    @RequestMapping("/openRegister")
    public ModelAndView getRegister(HttpServletRequest request) {
        Cookie[] reCommendCookies = request.getCookies();
        String htmlURL = "shoppingApi/user/register";
        ModelAndView modelAndView = new ModelAndView(htmlURL);
        if(reCommendCookies!=null){
            modelAndView.addObject("reCommendCookies", reCommendCookies[0].getValue());
        }

        return modelAndView;
    }

    //用户注册
    @ResponseBody
    @RequestMapping(value = "/userRegister", method = RequestMethod.POST)
    public Map<String, Object> userRegister(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String userNo = request.getParameter("userNo");
        String pwd = request.getParameter("pwd");
        String phone = request.getParameter("phone");
        String messageCode = request.getParameter("code");
        String messageCodeSession = "";
        try {
            messageCodeSession = request.getSession().getAttribute("regCode").toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String reCommendId = request.getParameter("reCommendId");

        double shareFinace3Balance = 0.00;//分享人折扣券余额
        int reCommendIds = 0;
        int userIds = 0;//用户ID
        String encryPwd = null;//加密后的密码
        String userName = null;//用户名
        if (!userNo.isEmpty() && !pwd.isEmpty() && !phone.isEmpty() && !messageCode.isEmpty()) {
            System.out.println(messageCode + "q-----q" + messageCodeSession);
            if (!messageCode.equals(messageCodeSession)) {
                map.put("msg", "0");
                return map;
            }
            boolean flag = VerifyData.getVerifyPhone(phone);
            User user = new User();
            try {
                user.setPwd(null);
                if (flag) {
                    user.setPhone(phone);
                }
                user.setUserName(userName);
                Timestamp timestamp = new Timestamp(System.currentTimeMillis());
                user.setRegisterTime(timestamp);
                //推荐人
                if (userIds != 0) {
                    user.setRecommend(userIds);
                } else {
                    userIds = 1;
                    user.setRecommend(userIds);
                }

                //等级
                user.setSort(0);
                user.setCardId(null);
                User users = userService.selectUserByPhone(phone);
                int rows = 0;
                int userId = 0;

                if (users == null) {
                    //用户表没数据时才新增用户
                    //保存用户
                    rows = userService.insert(user);
                    userId = user.getUserId();

                } else {
                    rows = 1;
                    userId = users.getUserId();
                }

                System.out.println("userId=" + userId);

                //注册用户的userNoId
                int registerUserNo1Id = 0;

                int shareUserNoIds = 0;

                UserNo userNo1 = new UserNo();

                //如果是微信浏览器
                if (com.yunshang.shoppingmall.common.weixin.UserRequest.IsWeixin(request)) {
                    //如果openid存在
                    HttpSession httpSession = request.getSession();
                    String openid = (String) httpSession.getAttribute("openid");
                    //查询是否存在openid
                    if (openid != null) {
                        UserNo userNo2 = sysUserNoService.selectUserNoByOpenid(openid);
                        if (userNo2 != null) {
                            if (userNo2.getRecommend() != null) {
                                shareUserNoIds = userNo2.getRecommend();
                                userNo1.setGhid(userNo2.getGhid());
                                userNo1.setOpenid(userNo2.getOpenid());
                            }

                            if (userNo2.getUserNo() != null) {
                                System.out.println("微信已经绑定");
                            } else {
                                //更新用户信息
                                // 保存用户编号
                                //默认游客
                                int rankId = 19;
                                userNo2.setUserId(userId);
                                userNo2.setRank(rankId);
                                userNo2.setAngel(0);
                                encryPwd = MD5Util.getEncryptedPwd(pwd);
                                userNo2.setPwd(encryPwd);
                                userNo2.setSort(0);
                                userNo2.setUserNo(userNo);
                                userNo2.setRegisterTime(new Timestamp(System.currentTimeMillis()));
                                if (sysUserNoService.updateByPrimaryKeySelective(userNo2) > 0) {
                                    registerUserNo1Id = userNo2.getId();
                                    shareUserNoIds = userNo2.getRecommend();
                                    request.getSession().setAttribute("userNo", userNo2);
                                    map.put("msg", "1");
                                }

                            }
                        }
                    }
                }

                if (registerUserNo1Id == 0) {

                    // 保存用户编号
                    userNo1.setName(null);
                    //默认游客
                    int rankId = 19;
                    userNo1.setUserId(userId);
                    userNo1.setRank(rankId);
                    userNo1.setSalt(null);
                    userNo1.setAngel(0);
                    encryPwd = MD5Util.getEncryptedPwd(pwd);
                    userNo1.setPwd(encryPwd);
                    userNo1.setSort(0);
                    userNo1.setUserNo(userNo);
                    userNo1.setPayPwd(null);
                    userNo1.setRegisterTime(new Timestamp(System.currentTimeMillis()));
                    if (shareUserNoIds == 0) {
                        //推荐人
                        shareUserNoIds = 62240;
                        String shareUserNoId = (String) request.getSession().getAttribute("shareUserNoId");
                        if (shareUserNoId == null || shareUserNoId == "") {//分享人的userNoId为空时，从cookies获取
                            Cookie[] cookies = request.getCookies();
                            for (int i = 0; i < cookies.length; i++) {
                                if (cookies[i].getName().equals("shareUserNoId")) {
                                    shareUserNoId = cookies[i].getValue();
                                    if (shareUserNoId == null || shareUserNoId == "") {
                                        shareUserNoIds = 62240;
                                    }
                                    break;
                                }
                            }
                        }

                        if (shareUserNoId != null && shareUserNoId != "") {
                            shareUserNoIds = Integer.parseInt(shareUserNoId);
                        }

                    }
                    //分享人的id
                    System.out.println("----------------分享人id---------->" + shareUserNoIds);
                    userNo1.setRecommend(shareUserNoIds);

                    //保存编号注册
                    if (sysUserNoService.insertSelective(userNo1) > 0) {
                        //注册用户的userNoId
                        registerUserNo1Id = userNo1.getId();

                        request.getSession().setAttribute("userNo", userNo1);
                        map.put("msg", "1");

                    }
                }

                if (registerUserNo1Id > 0 && rows > 0) {

                    //注册成功，赠送折扣券
                    Config config = configService.selectByPrimaryKey(1);

                    FinaceTotal finaceTotal = new FinaceTotal();
                    finaceTotal.setfType("3");//折扣券
                    finaceTotal.setUserId(registerUserNo1Id);//注册用户
                    finaceTotal.setOpratorUId(registerUserNo1Id);
                    finaceTotal.setChanggeTime(new Timestamp(System.currentTimeMillis()));
                    finaceTotal.setAmount(config.getGiftDiscount());
                    finaceTotal.setBalance(config.getGiftDiscount());
                    finaceTotal.setOpratorId(registerUserNo1Id);
                    int row1 = finaceTotalService.insertSelective(finaceTotal);//增加用户折扣券
                    FinaceTotal shareFinaceTotal = finaceTotalService.selectFinaceTotal(shareUserNoIds, "3");//推荐人的折扣券余额
                    int shareFId = 0;
                    if (shareFinaceTotal != null) {
                        shareFinace3Balance = shareFinaceTotal.getBalance();
                        shareFId = shareFinaceTotal.getfId();
                    }
                    finaceTotal.setUserId(shareUserNoIds);//推荐人id

                    //更新推荐人的折扣券
                    int shareRow = 0;
                    if (shareFinaceTotal != null) {//推荐人有折扣券的记录
                        finaceTotal.setBalance(config.getGiftDiscount() + shareFinace3Balance);//推荐人的折扣券余额
                        finaceTotal.setfId(shareFId);
                        shareRow = finaceTotalService.updateByPrimaryKey(finaceTotal);
                    } else {
                        finaceTotal.setBalance(config.getGiftDiscount());//推荐人的折扣券余额
                        shareRow = finaceTotalService.insertSelective(finaceTotal);
                    }

                    if (row1 > 0 && shareRow > 0) {//折扣券添加成功

                        //记录在折扣券表中
                        FinaceToData finaceToData = new FinaceToData();
                        finaceToData.setAmount(new BigDecimal(config.getGiftDiscount()));
                        finaceToData.setBalance(new BigDecimal(config.getGiftDiscount()));
                        finaceToData.setFinaceType("111");//注册赠送
                        finaceToData.setOpratorUId(registerUserNo1Id);
                        finaceToData.setOpratorId(registerUserNo1Id);
                        finaceToData.setFinaceTime(new Timestamp(System.currentTimeMillis()));
                        finaceToData.setRemark(userNo + "注册赠送");
                        finaceToData.setUserId(registerUserNo1Id);
                        finaceToData.setClassify(3);
                        int row2 = finaceService.insertFinaceData(finaceToData);

                        //记录推荐人的推荐用户注册获得折扣券的明细
                        finaceToData.setUserId(shareUserNoIds);
                        finaceToData.setBalance(new BigDecimal(config.getGiftDiscount() + shareFinace3Balance));
                        int recodeRow = finaceService.insertFinaceData(finaceToData);
                    }

                    return map;
                } else {
                    map.put("msg", "0");
                    return map;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        map.put("msg", "-1");
        return map;
    }

    /*验证注册的手机注册的账号个数*/
    @ResponseBody
    @RequestMapping("/verUserNoCountByPhone")
    public Map<String, Object> verUserNoCountByPhone(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        List<User> userList = null;
        int userId = 0;
        UserNo userNo = null;
        int counts = 0;
        String phone = request.getParameter("phone");
        if (phone != null && phone != "") {
            userList = userService.selectUserNoByPhone1(phone);
            map.put("userNoCount", userList.size());
        }
        return map;
    }


    //注册查询用户编号
    @ResponseBody
    @RequestMapping("/selectUserNoByUserNo")
    public Map<String, Object> selectUserNoByUserNo(String userNo) {
        logger.info("userNo:" + userNo);
        Map<String, Object> map = new HashMap<>();
        UserNo userNo1 = null;
        if (!userNo.isEmpty()) {
            //查询用户编号是否存在
            userNo1 = sysUserNoService.selectUserNoByUserNo(userNo);
            logger.info("userNo1:" + userNo1);
            map.put("userNo", userNo1);
            return map;
        } else {
            //用户编号不存在
            map.put("userNo", userNo1);
            return map;
        }

    }


    //密码登录
    /*打开用户名登录页面*/
    @RequestMapping("/openLoginPwd")
    public ModelAndView openLoginPwd(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("shoppingApi/user/loginbypassword");
        String currentURL = request.getParameter("currentURL");
        request.getSession().setAttribute("currentURL", currentURL);
        return modelAndView;
    }

    //用户密码登录
    @ResponseBody
    @RequestMapping(value = "/loginByPwd", method = RequestMethod.POST)
    public Map<String, Object> loginByPwd(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        boolean flag = false;
        String pwdInDb = null;
        String userNo = request.getParameter("userNo");
        String pwd = request.getParameter("pwd");
        if (!userNo.isEmpty() && !pwd.isEmpty()) {
            UserNo userNo1 = sysUserNoService.selectUserNoByUserNo(userNo);
            if (userNo1 != null) {
                pwdInDb = userNo1.getPwd();
                try {
                    if (null != pwdInDb) {
                        flag = MD5Util.validPassword(pwd, pwdInDb);//验证密码是否正确
                        if (flag) {
                            //session
                            request.getSession().setAttribute("userNo", userNo1);
                            request.getSession().setAttribute("phone", 1);
                            map.put("msg", "000001");//登录成功
                            map.put("userNo", userNo1);
                            return map;
                        } else {
                            map.put("msg", "000000");//登录失败
                            return map;
                        }
                    } else {
                        String par = "userid=" + userNo;
                        par += "&password=" + pwd;
                        par += "&clientIp=127.0.0.1";
                        par += "&encryptStr=60f5a3c2ab917609282ebaafc6365589";
                        String url = "http://yc.huisheng2688.com/hsycMgr/app/getUserInfo.do";
                        String json = HttpRequest.sendPost(url, par);
                        System.out.println(json);
                        HsysUserRoot hsysUserRoot = JSON.parseObject(json, HsysUserRoot.class);
                        if (hsysUserRoot.isSuccess()) {
                            System.out.println("A");

                            //读取User信息
                            User user = userService.selectByPrimaryKey(userNo1.getUserId());
                            if (user != null) {

                                HsysUserData hsysUserData = hsysUserRoot.data.get(0);

                                //更新数据,电话号码

                                boolean bit = false;
                                boolean bitn = false;

                                //判断是否改名
                                if (user.getUserName() != hsysUserData.getUsername()) {
                                    user.setUserName(hsysUserData.getUsername());
                                    userNo1.setName(hsysUserData.getUsername());
                                    bitn = true;
                                    bit = true;
                                }

                                //判断是否改身份证
                                if (user.getCardId() != hsysUserData.getIdcard()) {
                                    user.setCardId(hsysUserData.getIdcard());
                                    bit = true;
                                }

                                //判断是否改手机号码
                                if (user.getPhone() != hsysUserData.getCellphone()) {
                                    //修改的手机号是否存在
                                    User user1 = userService.selectUserByPhone(hsysUserData.getCellphone());
                                    if (user1 != null) {
                                        userNo1.setUserId(user1.getUserId());
                                        bitn = true;
                                    } else {
                                        user.setPhone(hsysUserData.getCellphone());
                                        bit = true;
                                    }

                                }

                                if (bit) {
                                    userService.updateByPrimaryKeySelective(user);
                                }

                                if (bitn) {
                                    userNoService.updateByPrimaryKeySelective(userNo1);
                                }

                                //session
                                request.getSession().setAttribute("userNo", userNo1);
                                request.getSession().setAttribute("phone", 1);
                                map.put("msg", "000001");//登录成功
                                map.put("userNo", userNo1);
                            } else {
                                System.out.println("U");
                                map.put("msg", "000000");//登录失败
                            }
                            return map;
                        } else {
                            System.out.println("B");
                            map.put("msg", "000000");//登录失败
                            return map;
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else {
                map.put("msg", MessageConstants.MSG_LOGIN_STATE0);
                return map;
            }
        }
        map.put("msg", MessageConstants.MSG_LOGIN_STATE2);
        return map;
    }

    /*打开手机登录页面*/
    @RequestMapping("/openLoginByPhone")
    @ResponseBody
    public ModelAndView openLoginByPhone1(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("shoppingApi/user/loginbyphone");
        String currentURL = request.getParameter("currentURL");
        request.getSession().setAttribute("currentURL", currentURL);
        return modelAndView;
    }

    //手机号登录
    @RequestMapping("/loginByPhone")
    @ResponseBody
    public Map<String, Object> loginByPhone(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String phone = request.getParameter("phone");
        String code = request.getParameter("code");
        String messageCodeSession = (String) request.getSession().getAttribute("regCode5");
        if (!phone.isEmpty() && !code.isEmpty()) {
            if (!code.equals(messageCodeSession)) {
                map.put("msg", "000002");
                return map;
            }
            User user = userService.selectUserByPhone(phone);
            System.out.println("手机号登录：" + user.toString());
            if (user != null) {
                request.getSession().setAttribute("userList", user);
                int userId = user.getUserId();
                List<UserNo> userNoList = userNoService.selectUserNoByUserId(userId);
                UserNo userNo = new UserNo();
                if (userNoList != null) {
                    if (userNoList.size() > 0) {
                        userNo = userNoList.get(0);//手机号登录 默认为绑定的手机号的第一个会员编号
                    }
                }
                System.out.println(userId);
                request.getSession().setAttribute("userNo", userNo);
                map.put("msg", "000001");
                map.put("userNo", userNo);
                String currentURL = (String) request.getSession().getAttribute("currentURL");
                map.put("currentURL", currentURL);
                request.getSession().setAttribute("phone", 2);
                return map;
            } else {
                map.put("msg", MessageConstants.MSG_LOGIN_PHONE1);
                return map;
            }

        } else {
            map.put("msg", MessageConstants.MSG_LOGIN_PHONE1);
            return map;
        }
    }

    //查询用户登录手机号
    @RequestMapping("/selectPhoneByPhone")
    @ResponseBody
    public Map<String, Object> selectPhoneByPhone(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String phone = request.getParameter("phone");
        if (!phone.isEmpty()) {
            User user = userService.selectUserByPhone(phone);
            if (user != null) {
                String phone1 = user.getPhone();
                map.put("phone", phone1);

                map.put("msg", MessageConstants.MSG_LOGIN_PHONE0);
                return map;
            } else {
                map.put("msg", MessageConstants.MSG_LOGIN_PHONE1);
                return map;
            }

        }
        map.put("msg", MessageConstants.MSG_LOGIN_PHONE1);
        return map;
    }

    //发送验证码
    @ResponseBody
    @RequestMapping("/sendCodeByPhone")
    public Map<String, Object> sendCodeByPhone(String phone, String type, HttpSession httpSession) {
        Map<String, Object> map = new HashMap<>();
        Config config = configService.selectByPrimaryKey(1);
        String json = "{\"stat\":\"666004\",\"message\":\"手机号码错误\"}";
        if (type.equals("1")) {//注册发送验证码
            if (OtherConstants.RegexpPhone(phone)) {
                List<User> users = userService.selectUserNoByPhone1(phone);
                if (users != null) {
                    if (users.size() >= 2) {
                        json = "{\"stat\":\"666010\",\"message\":\"同一手机号只能注册两个编号\"}";
                    } else {
                        String randomNumCode = Md5.getRandomNumCode(4);
                        String enRandomNumCode = "";
                        //加密验证码
                        try {
                            enRandomNumCode = randomNumCode;
                            if (config.getSmsType() == 1) {

                                json = SMSAPI.SMSAPI_Reg_code(phone, randomNumCode, config);

                            } else {
                                SendSmsResponse response = SmsDemo.sendSms(phone, randomNumCode);
                                if ("OK".equalsIgnoreCase(response.getCode())) {
                                    json = "{\"stat\":\"100\",\"message\":\"发送成功！\"}";
                                }
                            }
                            httpSession.setAttribute("regCode", enRandomNumCode);
                            httpSession.setAttribute("regPhone", phone);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }


                    }
                }
            }
        } else if (type.equals("2")) {//切换账号发送验证码
            String randomNumCode = Md5.getRandomNumCode(4);
            String enRandomNumCode = "";
            //加密验证码
            try {
                enRandomNumCode = randomNumCode;
                if (config.getSmsType() == 1) {
                    json = SMSAPI.SMSAPI_UserNo(phone, enRandomNumCode, config);
                } else {
                    SendSmsResponse response = SmsDemo.sendSms(phone, randomNumCode);
                    if ("OK".equalsIgnoreCase(response.getCode())) {
                        json = "{\"stat\":\"100\",\"message\":\"发送成功！\"}";
                    }
                }
                httpSession.setAttribute("regCode2", enRandomNumCode);
                httpSession.setAttribute("regPhone2", phone);


            } catch (Exception e) {
                e.printStackTrace();
            }

        } else if (type.equals("3")) {//找回密码1发送验证码
            String randomNumCode = Md5.getRandomNumCode(4);

            String enRandomNumCode = "";
            //加密验证码
            try {
                enRandomNumCode = randomNumCode;

                if (config.getSmsType() == 1) {
                    json = SMSAPI.SMSAPI_UserNo(phone, enRandomNumCode, config);
                } else {
                    SendSmsResponse response = SmsDemo.sendSms(phone, randomNumCode);
                    if ("OK".equalsIgnoreCase(response.getCode())) {
                        json = "{\"stat\":\"100\",\"message\":\"发送成功！\"}";
                    }
                }
                httpSession.setAttribute("regCode3", enRandomNumCode);
                httpSession.setAttribute("regPhone3", phone);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (type.equals("4")) {//找回密码2发送验证码
            String randomNumCode = Md5.getRandomNumCode(4);
            String enRandomNumCode = "";
            //加密验证码
            try {
                enRandomNumCode = randomNumCode;
                if (config.getSmsType() == 1) {
                    json = SMSAPI.SMSAPI_UserNo(phone, enRandomNumCode, config);
                } else {
                    SendSmsResponse response = SmsDemo.sendSms(phone, randomNumCode);
                    if ("OK".equalsIgnoreCase(response.getCode())) {
                        json = "{\"stat\":\"100\",\"message\":\"发送成功！\"}";
                    }
                }
                httpSession.setAttribute("regPhone4", phone);
                httpSession.setAttribute("regCode4", enRandomNumCode);

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (type.equals("5")) {//登录发送验证码
            if (OtherConstants.RegexpPhone(phone)) {


                String randomNumCode = Md5.getRandomNumCode(4);
                String enRandomNumCode = "";
                //加密验证码
                try {
                    enRandomNumCode = randomNumCode;
                    if (config.getSmsType() == 1) {
                        json = SMSAPI.SMSAPI_UserNo(phone, enRandomNumCode, config);
                    } else {
                        SendSmsResponse response = SmsDemo.sendSms(phone, randomNumCode);
                        if ("OK".equalsIgnoreCase(response.getCode())) {
                            json = "{\"stat\":\"100\",\"message\":\"发送成功！\"}";
                        }
                    }
                    httpSession.setAttribute("regPhone5", phone);
                    httpSession.setAttribute("regCode5", enRandomNumCode);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else if (type.equals("20")) {//微信绑定手机号验证
            String randomNumCode = Md5.getRandomNumCode(4);
            String enRandomNumCode = "";
            //加密验证码
            try {
                enRandomNumCode = randomNumCode;
                if (config.getSmsType() == 1) {
                    json = SMSAPI.SMSAPI_UserNo(phone, enRandomNumCode, config);
                } else {
                    SendSmsResponse response = SmsDemo.sendSms(phone, randomNumCode);
                    if ("OK".equalsIgnoreCase(response.getCode())) {
                        json = "{\"stat\":\"100\",\"message\":\"发送成功！\"}";
                    }
                }
                httpSession.setAttribute("regCode20", enRandomNumCode);
                httpSession.setAttribute("regPhone20", phone);


            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        map.put("json", json);
        return map;
    }


    //
    @ResponseBody
    @RequestMapping("/checkCode")
    public Response checkCode(HttpSession httpSession, HttpServletRequest request) {
        String messageCode = request.getParameter("code");
        String type = request.getParameter("type");
        String messageCodeSession = "";
        try {
            if (type.equals("2")) {
                messageCodeSession = (String) httpSession.getAttribute("regCode2");
            } else if (type.equals("3")) {
                messageCodeSession = (String) httpSession.getAttribute("regCode3");
            } else if (type.equals("4")) {
                messageCodeSession = (String) httpSession.getAttribute("regCode4");
            } else if (type.equals("5")) {
                messageCodeSession = (String) httpSession.getAttribute("regCode5");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!messageCode.equals(messageCodeSession)) {
            UserNo userNo1 = (UserNo) request.getSession().getAttribute("userNoCheckCode");
            if (userNo1 != null) {
                request.getSession().setAttribute("userNo", userNo1);
            }
            return new Response(MessageConstants.MSG_SYS_ERROR, 0, "");
        }
        return new Response(MessageConstants.MSG_SYS_ERROR, 1, "");
    }

    /*用户手机号登录切换用户编号登录*/
    @ResponseBody
    @RequestMapping("/changeUserNoByPhoneLogin")
    public Map<String, Object> changeUserNoByPhoneLogin(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String userNo = request.getParameter("userNo");
        List<User> userList = (List<User>) request.getSession().getAttribute("userList");
        UserNo userNo1 = null;
        int userId = 0;
        //查询用户ID
        if (userNo != null && userList != null) {
            userNo1 = sysUserNoService.selectUserNoByUserNo(userNo);
            if (userNo1 != null) {
                userId = userNo1.getUserId();
                System.out.println("userId===>" + userId);
                map.put("userId", userId);
            }
        }
        return map;

    }

    /*忘记密码*/
    @ResponseBody
    @RequestMapping("/forgetPwd")
    public ModelAndView forgetPwd(HttpServletRequest request) {
        String userNo = request.getParameter("userNo");
        ModelAndView modelAndView = null;
        if (userNo != null) {
            modelAndView = new ModelAndView("shoppingApi/user/changeloginpassword");
            User user = userService.selectPhoneByUserNo(userNo);
            if (user != null) {
                modelAndView.addObject("phone", user.getPhone());
            }
            modelAndView.addObject("userNo", userNo);
        } else {
            modelAndView = new ModelAndView("shoppingApi/user/loginbypassword");
        }
        return modelAndView;
    }

    /*修改密码*/
    @ResponseBody
    @RequestMapping(value = "/updatePwd", method = RequestMethod.POST)
    public Map<String, Object> updatePwd(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String pwd = request.getParameter("pwd");
        String userNo = request.getParameter("userNo");
        if (pwd != null && pwd != "" && userNo != null && userNo != "") {
            try {
                UserNo userNo1 = new UserNo();
                String encryptedPwd = MD5Util.getEncryptedPwd(pwd);
                userNo1.setPwd(encryptedPwd);
                userNo1.setUserNo(userNo);
                int row = sysUserNoService.updatePwdByUserNo(userNo1);
                if (row > 0) {
                    map.put("msg", "1");
                } else {
                    map.put("mag", "0");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return map;
    }


    @Transactional
    @ResponseBody
    @RequestMapping(value = "/updateHsUserInfo", method = RequestMethod.POST)
    public Response updateHsUserInfo(HttpServletRequest request) {
        String userNo = request.getParameter("userNo");
        String phone = request.getParameter("phone");
        String username = request.getParameter("userName");
        String registerTime = request.getParameter("registerTime");
        if (userNo != null && userNo != "" && phone != null && phone != "") {
            //查询手机号是否存在
            boolean flag = OtherConstants.RegexpPhone(phone);
            if (flag) {
//                User user=userService.selectUserByPhone(phone);
                UserNo userNo1 = userNoService.selectUserByUserNO(userNo);
                if (userNo1 != null) {
                    int userId = userNo1.getUserId();
                    List<UserNo> userNoList = userNoService.selectUserNoByUserId(userId);
                    if (userNoList.size() > 1) {//存在两个以上的账号，新增到用户表中，在修改该账号的用户ID
                        User us = new User();
                        us.setPhone(phone);
                        us.setUserName(username);
                        us.setRegisterTime(Timestamp.valueOf(registerTime));
                        int row = userService.insertSelective(us);
                        if (row > 0) {
                            int uId = us.getUserId();
                            userNo1.setUserId(uId);
                            int row1 = userNoService.updateByPrimaryKeySelective(userNo1);
                            if (row1 > 0) {
                                return new Response(MessageConstants.MSG_SUCCESS, true, 0, "");
                            } else {
                                throw new RuntimeException();
                            }

                        } else {
                            return new Response(MessageConstants.MSG_SUCCESS, false, 0, "添加更新数据失败！");
                        }
                    } else {//只有一个账号绑定的，就直接修改
                        User user = new User();
                        user.setPhone(phone);
                        user.setUserId(userId);
                        int row2 = userService.updateByPrimaryKeySelective(user);
                        if (row2 > 0) {
                            return new Response(MessageConstants.MSG_SUCCESS, true, 0, "");
                        } else {
                            return new Response(MessageConstants.MSG_SUCCESS, false, 0, "添加更新数据失败！");
                        }

                    }

                }


            } else {
                return new Response(MessageConstants.MSG_ILLEGAL_ARGUMENT, false, 0, "参数不能为空！");
            }


        }
        return new Response(MessageConstants.MSG_ILLEGAL_ARGUMENT, false, 0, "参数不能为空！");
    }

    /*打开微信登录绑定手机号页面*/
    @RequestMapping("/wechatPhone")
    public ModelAndView wechatPhone(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("shoppingApi/user/wechatPhone");

        HttpSession httpSession = request.getSession();

        httpSession.setAttribute("xPhone", "1");

        String shareUserNoId = (String) httpSession.getAttribute("shareUserNoId");
        if (shareUserNoId != null) {
            modelAndView.addObject("shareUserNoId", shareUserNoId);
        }

        return modelAndView;
    }

    /*邀请朋友进店*/
    @RequestMapping("/visitToStore")
    public ModelAndView wechatPhone() {
        ModelAndView modelAndView = new ModelAndView("shoppingApi/user/visitToStore");
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping("/userBinding")
    public Response userBinding(HttpServletRequest request, HttpServletResponse response) {

        String phone = request.getParameter("phone");
        String phoneCode = request.getParameter("phoneCode");

        String sCode = (String) request.getSession().getAttribute("regCode20");
        String sPhone = (String) request.getSession().getAttribute("regPhone20");

        System.out.println("phone:" + phone);
        System.out.println("phoneCode:" + phoneCode);
        System.out.println("sCode:" + sCode);
        System.out.println("sPhone:" + sPhone);

        String wOpenid = (String) request.getSession().getAttribute("wopenid");


        if (phone.equals(sPhone) && phoneCode.equals(sCode)) {
            User userLogin = new User();
            //读取绑定手机号
            User user = userService.selectUserByPhone(phone);
            if (user != null) //存在手机号
            {
                userLogin = user;
                if (user.getOpenid() == null)//没有绑定则绑定
                {
                    User user2 = new User();
                    user2.setUserId(user.getUserId());
                    user2.setOpenid(wOpenid);
                    int row = userService.updateByPrimaryKeySelective(user2);
                    if (row == 0)//绑定更新失败
                    {
                        return new Response(MessageConstants.MSG_ILLEGAL_ARGUMENT, false, 0, "绑定手机失败！");
                    }
                } else //手机号码已经绑定
                {
                    return new Response(MessageConstants.MSG_ILLEGAL_ARGUMENT, false, 0, "手机号码已经绑定微信公众号！");
                }
            } else //不存在号码,则注册
            {
                //添加User数据
                User user1 = new User();
                user1.setPhone(phone);
                user1.setOpenid(wOpenid);
                user1.setRegisterTime(new Timestamp(System.currentTimeMillis()));
                int row = userService.insertSelective(user1);
                if (row > 0) {
                    userLogin = user1;
                    //添加UserNo
                    UserNo userNo = new UserNo();
                    userNo.setUserNo("XLS" + phone);
                    String pwd = wOpenid.substring(2, 10);
                    System.out.println("PWD:" + pwd);
                    System.out.println(pwd);
                    try {
                        String encryptedPwd = MD5Util.getEncryptedPwd(pwd);
                        userNo.setPwd(encryptedPwd);
                    } catch (Exception ex) {
                        return new Response(MessageConstants.MSG_ILLEGAL_ARGUMENT, false, 0, "加密失败！");
                    }
                    userNo.setUserId(user1.getUserId());
                    userNo.setOpenid(wOpenid);
                    userNo.setRank(19);

                    //分享人
                    String ShareUserNoId = (String) request.getSession().getAttribute("shareUserNoId");
                    if (ShareUserNoId != null) {
                        userNo.setRecommend(Integer.parseInt(ShareUserNoId));
                    } else {
                        userNo.setRecommend(62240);
                        //return new Response(MessageConstants.MSG_ILLEGAL_ARGUMENT, false, 0, "分享人绑定失败！");
                    }

                    int row1 = sysUserNoService.insertSelective(userNo);
                    if (row1 > 0) {
                        //赠送代金券
                        //注册赠送
                        BigDecimal amount = new BigDecimal(100);
                        finaceService.insertTestFinace(3, amount, userNo.getId(), "XLS" + phone + "注册赠送", userNo.getId(), 0, 111);
                        finaceService.insertTestFinace(3, amount, userNo.getRecommend(), "XLS" + phone + "注册赠送", userNo.getId(), 0, 111);

                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                        String url = WinChat.severUrl;

                        //发送公众号消息
                        String txtJson1 = "\"first\": {\"value\":\"欢迎您加入荟品汇享（新零售微店）\",\"color\":\"#173177\"}," +
                                "\"keyword1\":{\"value\":\"" + phone + "\",\"color\":\"#173177\"}," +
                                "\"keyword2\":{\"value\":\"XLS" + phone + "\",\"color\":\"#173177\"}," +
                                "\"keyword3\":{\"value\":\"" + sdf.format(new Date()) + "\",\"color\":\"#173177\"}," +
                                "\"remark\":{\"value\":\"会员密码：" + pwd + "\",\"color\":\"#173177\"}";
                        String template_id = "UE4QSWZX9yxHBSTxtemMoorBmYsE_gme8NU8K9JusMc";
                        WinxinUtil.sendMessage(txtJson1, wOpenid, template_id, url);
                        System.out.println("已经发送公众号消息");

                        //发送分享人消息
                        if (ShareUserNoId != null) {
                            UserNo userNoS = sysUserNoService.selectByPrimaryKey(Integer.parseInt(ShareUserNoId));
                            if (userNoS != null) {
                                User userS = userService.selectByPrimaryKey(userNoS.getUserId());
                                if (userS != null && userS.getOpenid() != null) {
                                    //发送公众号消息
                                    String txtJson2 = "\"first\": {\"value\":\"恭喜您，有新的会员加入您的团队！\",\"color\":\"#173177\"}," +
                                            "\"keyword1\":{\"value\":\"XLS" + phone + "\",\"color\":\"#173177\"}," +
                                            "\"keyword2\":{\"value\":\"" + sdf.format(new Date()) + "\",\"color\":\"#173177\"}," +
                                            "\"keyword3\":{\"value\":\"二维码分享\",\"color\":\"#173177\"}," +
                                            "\"remark\":{\"value\":\"您的团队越来越强大了哦！！\",\"color\":\"#173177\"}";
                                    String template_id2 = "P0kBGXaA8F2Bdc1Zsz3eYmVKloRyXSqOB-tp3AmLr-k";
                                    WinxinUtil.sendMessage(txtJson2, userS.getOpenid(), template_id2, url);
                                    System.out.println("Text:" + txtJson2);
                                    System.out.println("SenOpenid:" + userS.getOpenid());
                                    System.out.println("已经发送分享人公众号消息");
                                }
                            }
                        }


                        //发送短信消息
                        Config config = configService.selectByPrimaryKey(1);
                        String json = SMSAPI.SMSAPI_Regin(phone, "XLS" + phone, pwd, config);
                        System.out.println("短信发送:" + json);

                    } else {
                        return new Response(MessageConstants.MSG_ILLEGAL_ARGUMENT, false, 0, "更新UserNo失败！");
                    }
                } else {
                    return new Response(MessageConstants.MSG_ILLEGAL_ARGUMENT, false, 0, "添加User失败！");
                }
            }

            //微信登录，相当于手机登录
            System.out.println(userLogin);
            request.getSession().setAttribute("userList", userLogin);
            UserNo userNoLogin = new UserNo();
            int userId = userLogin.getUserId();
            List<UserNo> userNoList = userNoService.selectUserNoByUserId(userId);
            if (userNoList != null) {
                if (userNoList.size() > 0) {
                    userNoLogin = userNoList.get(0);//手机号登录 默认为绑定的手机号的第一个会员编号
                }
            }
            if (userNoLogin != null) {
                System.out.println(userNoLogin);
                request.getSession().setAttribute("userNo", userNoLogin);
            }

            request.getSession().setAttribute("phone", 2);

            //转向
            String url = (String) request.getSession().getAttribute("weurl");
            request.getSession().setAttribute("dlopenid", wOpenid);

            System.out.println(url);
            System.out.println(wOpenid);

            System.out.println("AAAAAAAAAAAAAAAA");

            return new Response(MessageConstants.MSG_SUCCESS, url, 0, "绑定成功!!");

        } else {
            return new Response(MessageConstants.MSG_ILLEGAL_ARGUMENT, false, 0, "绑定失败！");
        }

        //return new Response(MessageConstants.MSG_SYS_ERROR, false, 0, "绑定失败！");
    }

    //手机号登录
    @ResponseBody
    @RequestMapping("/Share")
    public String Share(HttpServletRequest request, HttpServletResponse response) {

        String strLx = request.getParameter("lx");
        if (strLx != null) {
            String ShareUserNoId = request.getParameter("uid");

//            //添加Cookie
//            Cookie cookie = new Cookie("shareUserNoId", ShareUserNoId);
//            response.addCookie(cookie);

            //添加Session
            request.getSession().setAttribute("shareUserNoId", ShareUserNoId);

            int lx = Integer.parseInt(strLx);
            try {
                //转向
                if (lx == 1) {
                    response.sendRedirect("/");
                } else if (lx == 3) {
                    String productId = request.getParameter("productId");
                    String url = "/wap/getDetails?productId=" + productId;
                    response.sendRedirect(url);
                } else {
                    return "参数不对B";
                }
            } catch (Exception ex) {
                return "程序错误B";
            }
        } else {
            return "参数不对A";
        }
        return "程序错误A";
    }

    //手机号登录
    @ResponseBody
    @RequestMapping("/skip")
    public String skip(HttpServletRequest request, HttpServletResponse response) {
        String wOpenid = (String) request.getSession().getAttribute("wopenid");
        request.getSession().setAttribute("dlopenid", wOpenid);
        String url = (String) request.getSession().getAttribute("weurl");
        //转向
        try {
            response.sendRedirect(url);
        } catch (Exception ex) {
            return "程序错误C";
        }
        return "程序错误B";
    }

    //手机号登录
    @ResponseBody
    @RequestMapping("/xbcw")
    public String xbcw(HttpServletRequest request, HttpServletResponse response) {
        String suid = request.getParameter("uid");
        int uid = 0;
        try {
            uid = Integer.parseInt(suid);
        } catch (Exception ex) {

        }

        String key = request.getParameter("key");
        if(key==null || !key.equals("exmyleniscoptioscqm")) {
            return "KEYCODE";
        }
        if (uid > 0) {
            UserNo userNo = sysUserNoService.selectByPrimaryKey(uid);
            if (userNo != null) {
                int ShareUserNoId = userNo.getRecommend();
                User user = userService.selectByPrimaryKey(userNo.getUserId());
                if (user != null) {
                    String phone = user.getPhone();
                    String wOpenid = user.getOpenid();
                    String pwd = wOpenid.substring(2, 10);
                    //赠送代金券
                    //注册赠送
                    BigDecimal amount = new BigDecimal(100);
                    finaceService.insertTestFinace(3, amount, userNo.getId(), "XLS" + phone + "注册赠送", userNo.getId(), 0, 111);
                    finaceService.insertTestFinace(3, amount, userNo.getRecommend(), "XLS" + phone + "注册赠送", userNo.getId(), 0, 111);

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                    String url = WinChat.severUrl;

                    //发送公众号消息
                    String txtJson1 = "\"first\": {\"value\":\"欢迎您加入荟品汇享（新零售微店）\",\"color\":\"#173177\"}," +
                            "\"keyword1\":{\"value\":\"" + phone + "\",\"color\":\"#173177\"}," +
                            "\"keyword2\":{\"value\":\"XLS" + phone + "\",\"color\":\"#173177\"}," +
                            "\"keyword3\":{\"value\":\"" + sdf.format(new Date()) + "\",\"color\":\"#173177\"}," +
                            "\"remark\":{\"value\":\"会员密码：" + pwd + "\",\"color\":\"#173177\"}";
                    String template_id = "UE4QSWZX9yxHBSTxtemMoorBmYsE_gme8NU8K9JusMc";
                    WinxinUtil.sendMessage(txtJson1, wOpenid, template_id, url);
                    System.out.println("已经发送公众号消息");

                    //发送分享人消息
                    UserNo userNoS = sysUserNoService.selectByPrimaryKey(ShareUserNoId);
                    if (userNoS != null) {
                        User userS = userService.selectByPrimaryKey(userNoS.getUserId());
                        if (userS != null && userS.getOpenid() != null) {
                            //发送公众号消息
                            String txtJson2 = "\"first\": {\"value\":\"恭喜您，有新的会员加入您的团队！\",\"color\":\"#173177\"}," +
                                    "\"keyword1\":{\"value\":\"XLS" + phone + "\",\"color\":\"#173177\"}," +
                                    "\"keyword2\":{\"value\":\"" + sdf.format(new Date()) + "\",\"color\":\"#173177\"}," +
                                    "\"keyword3\":{\"value\":\"二维码分享\",\"color\":\"#173177\"}," +
                                    "\"remark\":{\"value\":\"您的团队越来越强大了哦！！\",\"color\":\"#173177\"}";
                            String template_id2 = "P0kBGXaA8F2Bdc1Zsz3eYmVKloRyXSqOB-tp3AmLr-k";
                            WinxinUtil.sendMessage(txtJson2, userS.getOpenid(), template_id2, url);
                            System.out.println("Text:" + txtJson2);
                            System.out.println("SenOpenid:" + userS.getOpenid());
                            System.out.println("已经发送分享人公众号消息");
                        }
                    }


                    //发送短信消息
                    Config config = configService.selectByPrimaryKey(1);
                    String json = SMSAPI.SMSAPI_Regin(phone, "XLS" + phone, pwd, config);
                    System.out.println("短信发送:" + json);
                    return "成功";
                }
            }
        }
        return "错误";
    }
}